package com.ctrlspace.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ctrlspace.core.managers.UserManager;
import com.ctrlspace.model.HttpAttributes;
import com.ctrlspace.model.HttpMappings;
import com.ctrlspace.model.User;

/**
 * Servlet implementation class SessionServlet
 */
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User currentUser = (User) session.getAttribute(HttpAttributes.CURRENT_USER);
		
		// No one logged in yet
		if (currentUser == null) {
			// Check post attributes
			String loginSubmit = request.getParameter("login");
			
			// POST was done
			if (loginSubmit != null) {
				String username = request.getParameter("username");
				String password = request.getParameter("password");
				
				currentUser = UserManager.getInstance().getUser(username, password);
				
				// Success
				if (currentUser != null) {
					currentUser.setLogged(true);
					session.setAttribute(HttpAttributes.CURRENT_USER, currentUser);
					
					// Redirect to IDE
					response.sendRedirect(HttpMappings.BASE_URL + HttpMappings.IDE_SERVLET);
					return;
				}
				
				// Set error
				request.setAttribute(HttpAttributes.ERROR_MESSAGE, new String[]{"Invalid login credentials."});
			}
			
			// Forward to login page
			RequestDispatcher rd = request.getRequestDispatcher(HttpMappings.LOGIN_PAGE);
			rd.forward(request, response);
			return;
		}
		
		// Someone is logged in, just need to get info of user maybe?
		response.getWriter().write(currentUser.toJSONString());
		return;
	}
}